package com.example.coffeesystem.service.impl;

import com.example.coffeesystem.utils.Result;
import com.example.coffeesystem.dao.StaffDao;
import com.example.coffeesystem.service.StaffServicce;
import com.example.coffeesystem.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class StaffServiceImpl implements StaffServicce {

    @Autowired
    private StaffDao staffDao;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public Result findAll(){
        log.info("获取用户信息");
        return Result.success("用户获取信息成功", staffDao.findAll());
    }

    @Override
    public Result login(LoginVo loginVo) {
        log.info("1.开始登录");
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginVo.getUsername());
        log.info("2.判断账户是否存在，密码是否正确");
        if(null==userDetails||passwordEncoder.matches(loginVo.getPassword(),userDetails.getPassword())){
            return Result.fail("密码错误，请重新登录");
        }
        log.info("3.判断账号是否已经被禁用");
        if(!userDetails.isEnabled()){
            return Result.fail("该账号已经禁用");
        }
        log.info("4.登录成功，在security对象中存在登录者信息");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        log.info("5.根据登录信息获取Token");
        //需要借助JWT来生成Token
        String token="";
        Map<String,String> map = new HashMap<>(2);
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        return Result.success("登录成功",map);
    }
}
